﻿using System;
using System.Messaging;

namespace NsbMonitorClientService.QueueManager
{
    public class CountMessagesInQueue : ICountMessagesInQueue
    {
        public int CountMessages(MessageQueue q)
        {
            int count = 0;

            Cursor cursor = q.CreateCursor();

            Message current = PeekWithoutTimeout(q, cursor, PeekAction.Current);
            if (current != null)
            {
                count = 1;

                while (PeekWithoutTimeout(q, cursor, PeekAction.Next) != null)
                {
                    count++;
                }
            }

            return count;
        }

        protected Message PeekWithoutTimeout(MessageQueue q, Cursor cursor, PeekAction action)
        {
            Message ret = null;

            try
            {
                ret = q.Peek(new TimeSpan(1), cursor, action);
            }

            catch (MessageQueueException mqe)
            {
                if (mqe.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
                {
                    throw;
                }
            }

            return ret;
        }
    }
}